package com.py.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.py.payment.dto.ret.MonitorRetDto;
import com.py.payment.entity.EarlyInfo;
import com.py.payment.entity.EarlyLevelConfig;
import com.py.payment.entity.Monitor;
import com.py.payment.mapper.EarlyLevelConfigMapper;
import com.py.payment.service.EarlyLevelConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.py.payment.tools.ToolsUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 预警等级配置 服务实现类
 * </p>
 *
 * @author py
 * @since 2024-05-21
 */
@Service
public class EarlyLevelConfigServiceImpl extends ServiceImpl<EarlyLevelConfigMapper, EarlyLevelConfig> implements EarlyLevelConfigService {


    @Override
    public List<EarlyLevelConfig> getEarlyConfigList() {
        QueryWrapper<EarlyLevelConfig> earlyLevelConfigQueryWrapper = new QueryWrapper<>();
        earlyLevelConfigQueryWrapper.orderByAsc("level");
        List<EarlyLevelConfig> list = this.list(earlyLevelConfigQueryWrapper);
        return list;
    }

    @Override
    public List<EarlyInfo> earlyRating(List<Monitor> monitorList) {
        List<EarlyInfo> earlyInfoList = new ArrayList<>();
        List<EarlyLevelConfig> configList = getEarlyConfigList();
        monitorList.forEach(item->{
            if(!ToolsUtils.isEmpty(item.getEarly())) {
                if (item.getActual().compareTo(item.getEarly()) > 0) {
                    EarlyInfo earlyInfo = new EarlyInfo();
                    earlyInfo.setActual(item.getActual());
                    earlyInfo.setPointId(item.getPointId());
                    earlyInfo.setMonitorType(item.getMonitorType());
                    earlyInfo.setCreateTime(item.getCreateTime());
                    for (EarlyLevelConfig config : configList) {
                        if (config.getIsEdge() == 1) {
                            earlyInfo.setEarlyLevel(config.getLevel());
                            earlyInfoList.add(earlyInfo);
                            break;
                        }
                        BigDecimal deviation = item.getActual().subtract(item.getEarly());
                        BigDecimal product = item.getEarly().multiply(config.getVerificationValue().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
                        if (deviation.compareTo(product) <= 0) {
                            earlyInfo.setEarlyLevel(config.getLevel());
                            earlyInfoList.add(earlyInfo);
                            break;
                        }
                    }
                }
            }
        });
        return earlyInfoList;
    }
}
